﻿using Defarm.Helpers;
using Defarm.Model;
using Defarm.Model.Common;
using Defarm.View;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace Defarm.ViewModel 
{
    public class LoginViewModel : ViewModelBase
    {
        #region Fields

        private Chemist chemist;

        private LoginWindow loginWindow;

        private string login;

        private string password;

        private bool isOk;

        private RelayCommand doLogin;

        #endregion

        #region Public properties

        public LoginWindow LoginWindow
        {
            get
            {
                return this.loginWindow;
            }

            set
            {
                this.loginWindow = value;
                this.RaisePropertyChanged(() => this.LoginWindow);
            }
        }

        public string Login
        {
            get
            {
                return this.login;
            }

            set
            {
                this.login = value;
                this.RaisePropertyChanged(() => this.Login);
            }
        }

        public string Password
        {
            get
            {
                return this.password;
            }

            set
            {
                this.password = value;
                this.RaisePropertyChanged(() => this.Password);
            }
        }

        public bool IsOk
        {
            get
            {
                return this.isOk;
            }

            set
            {
                this.isOk = value;
                this.RaisePropertyChanged(() => this.IsOk);
            }
        }

        public Chemist Chemist
        {
            get
            {
                return this.chemist;
            }

            set
            {
                this.chemist = value;
                this.RaisePropertyChanged(() => this.Chemist);
            }
        }

        #endregion

        #region Commands

        public RelayCommand DoLogin
        {
            get
            {
                if (this.doLogin == null)
                {
                    this.doLogin = new RelayCommand(() =>
                    {
                        var answer = DbHelper.CheckCredentials(this.Login, this.Password);
                        if (answer != null)
                        {
                            this.IsOk = true;
                            this.Chemist = DbHelper.GetCityOrganisation(answer);
                            this.LoginWindow.Close();
                        }
                    });
                }

                return this.doLogin;
            }
        }

        #endregion
    }
}
